/*----------------------------------------------------------------------------
 * Copyright (c) <2016-2020>, <Huawei Technologies Co., Ltd>
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *---------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 *---------------------------------------------------------------------------*/
#include "usart.h"
#include "stm32f4xx.h"
#include <los_hwi.h>

#include "omip.h"
#include "omip_uart.h"
#if AR501C_ETH
        static USART_TypeDef*     s_pUSART = USART2;
        static uint32_t           s_uwIRQn = USART2_IRQn;
#endif
typedef void (*omip_irq_func)(void);

typedef struct {
    USART_TypeDef        *pusart;
    UART_HandleTypeDef   uhandle;
    uint32_t             irqn;
    omip_irq_func        irq_func;
}uart_entry;


void omip_uart3_irq(void);
void omip_uart2_irq(void);


uart_entry g_entrys[OMIP_SUPPORT_MAX_PYS_DEV_NUM];

void omip_uart_irq_common(UART_HandleTypeDef *huart, int io_id)
{
    uint32_t isrflags   = READ_REG(huart->Instance->SR);
    uint32_t cr1its     = READ_REG(huart->Instance->CR1);
    uint32_t cr3its     = READ_REG(huart->Instance->CR3);
    uint32_t errorflags = 0x00U;

    uint32_t ErrorCode  = HAL_UART_ERROR_NONE;
    uint8_t data;
    extern struct omip_context_tag  *omip_get_context(void);
    struct omip_context_tag  *context = omip_get_context();
    omip_io_paras   *io = context->io_p[io_id];

    /* If no error occurs */
    errorflags = (isrflags & (uint32_t)(USART_SR_PE | USART_SR_FE | USART_SR_ORE | USART_SR_NE));
    if(errorflags == RESET)
    {
        /* UART in mode Receiver -------------------------------------------------*/
        if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
        {
            data = (uint8_t)(huart->Instance->DR & 0x00FF);
            io->inject_recv_byte(data, io_id);
            return;
        }
    }

    /* If some errors occur */
    if((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET) || ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET)))
    {
        /* UART parity error interrupt occurred ----------------------------------*/
        if(((isrflags & USART_SR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET))
        {
            ErrorCode |= HAL_UART_ERROR_PE;
        }

        /* UART noise error interrupt occurred -----------------------------------*/
        if(((isrflags & USART_SR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
        {
            ErrorCode |= HAL_UART_ERROR_NE;
        }
    
        /* UART frame error interrupt occurred -----------------------------------*/
        if(((isrflags & USART_SR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
        {
            ErrorCode |= HAL_UART_ERROR_FE;
        }
    
        /* UART Over-Run interrupt occurred --------------------------------------*/
        if(((isrflags & USART_SR_ORE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
        { 
            ErrorCode |= HAL_UART_ERROR_ORE;
        }

        /* Call UART Error Call back function if need be --------------------------*/    
        if(ErrorCode != HAL_UART_ERROR_NONE)
        {
            /* UART in mode Receiver -----------------------------------------------*/
            if(((isrflags & USART_SR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
            {
                data = (uint8_t)(huart->Instance->DR & 0x00FF);
            }
            printf("omip_uart_irq_common ErrorCode:%lx %d\n",ErrorCode,__LINE__);
        }
    } 
}

void omip_uart3_irq(void)
{
    omip_uart_irq_common(&g_entrys[0].uhandle,0);
}

void omip_uart2_irq(void)
{
    omip_uart_irq_common(&g_entrys[1].uhandle,1);
}

void omip_uart_init(void)
{
    //initialize the slip_uart
    int i;
    int num = sizeof(g_entrys)/sizeof(uart_entry);
   
    g_entrys[0].pusart = USART2;
    g_entrys[0].irqn = USART2_IRQn;
    g_entrys[0].irq_func = omip_uart3_irq;
    
    g_entrys[1].pusart = USART6;
    g_entrys[1].irqn = USART6_IRQn;
    g_entrys[1].irq_func = omip_uart2_irq;

    for(i = 0;i < num; i++)
    {
        g_entrys[i].uhandle.Instance = g_entrys[i].pusart;
        g_entrys[i].uhandle.Init.BaudRate = 115200;
        g_entrys[i].uhandle.Init.WordLength = UART_WORDLENGTH_8B;
        g_entrys[i].uhandle.Init.StopBits = UART_STOPBITS_1;
        g_entrys[i].uhandle.Init.Parity = UART_PARITY_NONE;
        g_entrys[i].uhandle.Init.Mode = UART_MODE_TX_RX;
        g_entrys[i].uhandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
        g_entrys[i].uhandle.Init.OverSampling = UART_OVERSAMPLING_16;

        if (HAL_UART_Init(&g_entrys[i].uhandle) != HAL_OK)
        {
            _Error_Handler(__FILE__, __LINE__);
        }

        //create a hardware interrupt to deal slip_uart_irq
        LOS_HwiCreate(g_entrys[i].irqn, 3, 0, g_entrys[i].irq_func, 0);

        __HAL_UART_CLEAR_FLAG(&g_entrys[i].uhandle,UART_FLAG_TC);

        __HAL_UART_ENABLE_IT(&g_entrys[i].uhandle,UART_IT_ERR);
         __HAL_UART_ENABLE_IT(&g_entrys[i].uhandle,UART_IT_PE);
        //enable slip_uart UART_IT_RXNE interrupt
        __HAL_UART_ENABLE_IT(&g_entrys[i].uhandle,UART_IT_RXNE);//Receive Data register not empty interrupt

        __HAL_UART_ENABLE(&g_entrys[i].uhandle);
    }
}

void omip_send_byte(unsigned char data, unsigned int io_id)
{

    if(io_id < OMIP_SUPPORT_MAX_PYS_DEV_NUM)
        HAL_UART_Transmit(&g_entrys[io_id].uhandle,&data,1,100);
}

